package com.ctcemti.mdm.project.sys.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.ctcemti.mdm.common.result.Result;
import com.ctcemti.mdm.common.result.ResultEnum;
import com.ctcemti.mdm.common.util.*;
import com.ctcemti.mdm.project.common.excelverifyhandler.ExcelVerifyHandlerToOrgPerson;
import com.ctcemti.mdm.project.sys.dao.InfDictItemMapper;
import com.ctcemti.mdm.project.sys.dao.LoginLogMapper;
import com.ctcemti.mdm.project.sys.dao.OrgPersonMapper;
import com.ctcemti.mdm.project.sys.entity.*;
import com.ctcemti.mdm.project.sys.service.ICommonService;
import com.ctcemti.mdm.project.sys.service.ICompanyService;
import com.ctcemti.mdm.project.sys.service.IOrgPersonService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @ClassName InfDisciplinesMapper
 * @Description 专业领域逻辑层接口层
 * @Author bxf
 * @Date 11:20 2019/7/12
 * @Version V1.0
 **/
@Service
@Slf4j
public class OrgPersonServiceImpl implements IOrgPersonService {

    @Autowired
    private OrgPersonMapper orgPersonMapper;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private ICommonService commonService;

    @Autowired
    private InfDictItemMapper infDictItemMapper;

    @Autowired
    private LoginLogMapper loginLogMapper;

    @Autowired
    private RedisUtil redisUtil;


    @Value("${ctcemti.uploadfilepath}")
    private  String uploadfilepath;

    @Value("${ctcemti.errorfilepath}")
    private String errorfilepath;



    /**
     * @param
     * @return
     * @Author pzw
     * @Description 新增
     * @Date 11:39 2019/7/18
     * @Param
     */
    @Override
    @Transactional
    public Result<OrgPerson> insert(OrgPerson orgPerson,MultipartFile file) {
        String filepath="";
        if (StringUtils.isNotBlank(file.getOriginalFilename())) {
            filepath= FileUploadUtils.uploadFile(file,uploadfilepath);
            if(filepath==null){
                return new Result<OrgPerson>(ResultEnum.ZTSJ_1021,null);
            }
            orgPerson.setImage(filepath);
        }
        orgPerson.setPassword(Md5Utils.getMD5("888888"));
        orgPerson.setId(UUID.randomUUID().toString());
        //插入用户
        orgPersonMapper.insertSelective(orgPerson);
        //插入关系表
        orgPersonMapper.insertOrgRerson(orgPerson);
        //插入关系表
        String str=orgPerson.getRoleId();
        List<OrgPersonDomain> list=new ArrayList<>();
        if(str!=null&&str!=""){
            String[] split = str.split(",", -1);
            for (String s : split) {
                OrgPersonDomain o=new OrgPersonDomain();
                o.setPersonId(orgPerson.getId());
                o.setRoleId(s);
                list.add(o);
            }
        }
        orgPersonMapper.insertRelRole(list);

        return new Result<OrgPerson>(ResultEnum.SUCCESS,null);
    }

    /**
     * @param orgPerson
     * @return
     * @Author pzw
     * @Description 分页查询
     * @Date 11:39 2019/7/18
     * @Param
     */
    @Override
    public List<OrgPerson> selectAllOrgPerson(OrgPerson orgPerson) {
        return orgPersonMapper.selectAllOrgPerson(orgPerson);
    }

    /* *
     * @Author bxf
     * @Description 分页查询(排除已绑定角色的人员获取查查寻已绑定的人员)
     * @Date 18:10 2019/8/23
     * @param orgPerson
     * @return java.util.List<com.ctcemti.mdm.project.sys.entity.OrgPerson>
     */
    @Override
    public List<OrgPerson> selectAllOrgPersonNoRoleOrHasRole(OrgPerson orgPerson, Integer flag) {
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("orgId",orgPerson.getOrgId());
        params.put("roleId",orgPerson.getRoleId());
        params.put("flag",flag);
        params.put("name",orgPerson.getName());
        return orgPersonMapper.selectAllOrgPersonNoRoleOrHasRole(params);
    }

    /**
     * @param orgPerson
     * @return
     * @Author pzw
     * @Description 根据条件查询实体
     * @Date 11:39 2019/7/18
     * @Param
     */
    @Override
    public List<OrgPerson> selectOrgPerson(OrgPerson orgPerson) {
        return orgPersonMapper.select(orgPerson);
    }

    /**
     * @param orgPerson
     * @return
     * @Author pzw
     * @Description 修改
     * @Date 11:39 2019/7/18
     * @Param
     */
    @Override
    @Transactional
    public  Result<OrgPerson>  updateOrgPerson(OrgPerson orgPerson,MultipartFile file) {
        String filepath="";
        if (StringUtils.isNotBlank(file.getOriginalFilename())) {
            filepath= FileUploadUtils.uploadFile(file,uploadfilepath);
            if(filepath==null){
                return new Result<OrgPerson>(ResultEnum.ZTSJ_1021,null);
            }
            orgPerson.setImage(filepath);

        }
        String[] ids=new String[]{orgPerson.getId()};
        orgPersonMapper.deleteRelRole(ids);
        String str=orgPerson.getRoleId();
        List<OrgPersonDomain> list=new ArrayList<>();
        if(str!=null&&str!=""){
            String[] split = str.split(",", -1);
            for (String s : split) {
                OrgPersonDomain o=new OrgPersonDomain();
                o.setPersonId(orgPerson.getId());
                o.setRoleId(s);
                list.add(o);
            }
        }
        orgPersonMapper.insertRelRole(list);
        return new Result<OrgPerson>(ResultEnum.SUCCESS,orgPersonMapper.updateOrgPerson(orgPerson));
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int deleteOrgPerson(String[] ids) {
        String ids_str = StringUtils.join(ids, ",");
        ids_str = ids_str.replace(",", "','");
        ids_str="'"+ids_str+"'";
        orgPersonMapper.deleteRelOrg(ids);
        orgPersonMapper.deleteRelRole(ids);
        return orgPersonMapper.deleteByIds(ids_str);
    }

    /**
     * @param orgPerson
     * @return
     * @Author pzw
     * @Description 登录名是否存在
     * @Date 11:39 2019/7/18
     * @Param
     */
    @Override
    public int hasOrgPerson(OrgPerson orgPerson) {
        return orgPersonMapper.hasOrgPerson(orgPerson);
    }

    /**
     * @param orgPerson
     * @return
     * @Author pzw
     * @Description 查询组织树
     * @Date 11:39 2019/7/18
     * @Param
     */
    @Override
    public List<OrgOrganization> selectOrgTree(OrgPerson orgPerson,String token) {
//        return orgPersonMapper.selectOrgTree("3");
        if("Administrator".equals(JWTUtil.getLoginName(token))){
            return  orgPersonMapper.selectOrgTreeByAdmin();
        }
        List<OrgOrganization> list = companyService.getByPersonId(JWTUtil.getLoginId(token)).getData();
        return orgPersonMapper.selectOrgTree(list);
    }

    /**
     * @param ids
     * @param orgids
     * @param retain
     * @return
     * @Author pzw
     * @Description 移动
     * @Date 11:39 2019/7/18
     * @Param
     */
    @Override
    @Transactional
    public int moveOrgPerson(String[] ids, String[] orgids, Boolean retain) {
        //不保留原关系
        if(!retain){
            orgPersonMapper.deleteRelOrg(ids);
        }
        List<OrgPersonDomain> list=new ArrayList<>();
        for (String id : ids) {
            for (String orgid : orgids) {
                list.add(new OrgPersonDomain(id,orgid));
            }
        }
        return orgPersonMapper.moveOrgPerson(list);
    }

    /**
     * @param multipartFile
     * @param orgId
     * @param response
     * @return
     * @Author 导入
     * @Description 移动
     * @Date 11:39 2019/7/18
     * @Param
     */
    @Override
    @Transactional
    public Map<String, Object> uploadFile(MultipartFile multipartFile, String orgId, HttpServletResponse response, HttpServletRequest request) throws IOException, NoSuchAlgorithmException {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        ExcelImportResult<OrgPerson> excelImportResult = ExcelParseUtils.
                importExcelMore(multipartFile,0,1,OrgPerson.class,new ExcelVerifyHandlerToOrgPerson(orgPersonMapper,infDictItemMapper));
        boolean flag = true;
        if(excelImportResult.getFailList().size()>0){//验证失败，重新写入excel，并保存
            String filename = UUID.randomUUID().toString();//获取新的文件名
            File folder = new File(errorfilepath);//文件夹
            if(!folder.exists()){
                boolean mkFlag = folder.mkdirs();
                if (mkFlag) {
                    log.error("未找到上传文件夹，新建文件夹");
                }
            }
            FileOutputStream fos = null;
            try {
                //fileOutputStream = new FileOutputStream(file);
                //excelImportResult.getWorkbook().write(fileOutputStream);
                List<OrgPerson> slist = excelImportResult.getList();//获取所有成功项
                List<OrgPerson> flist = excelImportResult.getFailList();//获取所有失败项
                slist.addAll(flist);
                Collections.sort(slist);
                ExportParams exportParams = new ExportParams(null,null,"错误列表");
                exportParams.setStyle(ExcelExportStylerImpl.class);
                Workbook workbook = ExcelExportUtil.exportExcel(exportParams,OrgPerson.class, slist);
                fos = new FileOutputStream(errorfilepath+"/"+filename+".xls");
                workbook.write(fos);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(fos!=null){
                    fos.close();
                }
            }
            flag = false;
            resultMap.put("flag",flag);
            resultMap.put("filecode",filename);

        }else{
            //成功验证，准备导入数据
            List<OrgPerson> list = excelImportResult.getList();
            String loginId = JWTUtil.getLoginId(request.getHeader("Authorization"));
            for (OrgPerson orgPerson : list) {
                orgPerson.setCreator(loginId);
                String uuid = UUID.randomUUID().toString();
                orgPerson.setOrgId(orgId);
                orgPerson.setId(uuid);
                orgPerson.setPassword(Md5Utils.getMD5("888888"));
            }
            //工艺工法库插入
            BatchOperationUtils<OrgPerson> batchOperationUtils = new BatchOperationUtils();
            batchOperationUtils.batchOperation(list, 200,var->orgPersonMapper.insertBatch(var));
            BatchOperationUtils<OrgPerson> batchOperationUtils2 = new BatchOperationUtils();
            batchOperationUtils.batchOperation(list, 200,var->orgPersonMapper.insertRelBatch(var));
            resultMap.put("flag",flag);
        }
        return resultMap;
    }

    /* *
     * @Author bxf
     * @Description 登陆验证
     * @Date 22:38 2019/8/24
     * @param orgPerson
     * @return int
     */
    @Override
    public Result loginSystem(HttpServletRequest request,OrgPerson orgPerson) throws NoSuchAlgorithmException {
        int flag = orgPersonMapper.hasOrgPerson(orgPerson);
        if(StringUtil.isEmpty(orgPerson.getLoginName()) || StringUtil.isEmpty(orgPerson.getPassword())){
            return new Result(ResultEnum.ZTSJ_1004,null);
        }
        if(flag<0){
            return new Result(ResultEnum.ZTSJ_1002,null);
        }
        List<OrgPerson> list = orgPersonMapper.select(orgPerson);
        if(list.size()<1){
            return new Result(ResultEnum.ZTSJ_1003,null);
        }
        String loginName = list.get(0).getLoginName();
        String personId = list.get(0).getId();
        String token = JWTUtil.generateToken(loginName,personId);
        // 获取IP地址
        //String ip = request.getRemoteAddr();//使用反向代理后无法获取真实ip
        String ip = MacUtils.getIpAddress(request);
        // 获取浏览器信息
        String name = MacUtils.getBrowser(request);
        LoginLog record = new LoginLog();
        record.setDeviceName(name);
        record.setIpAdress(ip);
        record.setLoginType(1);
        record.setLoginTime(new Date());
        record.setLoginName(personId);
        //登录日志
        loginLogMapper.insertLoginLog(record);
        return new Result(ResultEnum.SUCCESS,token);
    }


    @Override
    public List<OrgRole> selectOrgRole(OrgPerson orgPerson) {
        return orgPersonMapper.selectOrgRole(orgPerson);
    }

    @Override
    public int changePassWord(OrgPerson person,Integer flag) {
        if(flag==1){
            return orgPersonMapper.select(person).size();
        }else{
            return orgPersonMapper.updateByPrimaryKeySelective(person);
        }

    }
    @Override
    public List<OrgPerson> selectOrgPersonByIds(String ids) {
        Example example = new Example(OrgPerson.class);
        Example.Criteria criteria = example.createCriteria();
        String id[] = ids.split(",");
        for(int i=0;i<id.length;i++){
            criteria.orEqualTo("id",id[i]);
        }
        return orgPersonMapper.selectByExample(example);
    }

}